package cn.wolfcode.luowowo.website.web.resolve;

import cn.wolfcode.luowowo.cache.service.IUserRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annoation.UserParam;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户对象参数解析
 */
public class UserInfoResolver implements HandlerMethodArgumentResolver {
    @Reference
    private IUserRedisService userRedisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == UserInfo.class && methodParameter.hasParameterAnnotation( UserParam.class );
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest( HttpServletRequest.class );
        HttpServletResponse response = nativeWebRequest.getNativeResponse( HttpServletResponse.class );
        String token = CookieUtil.getToken( request, response );
        UserInfo userInfo = userRedisService.getUserInfoByToken( token );
        return userInfo;
    }
}
